<?php

?><!DOCTYPE HTML>
<html lang="en">
<head>
<style>
#loading {
  margin:50px auto;
  position:fixed;
  width:100%;
  height:100%;
  text-align:center;
}

#loading_container {
  position:relative;
  margin:0 auto;
  width:200px;
  height:20px;
  border:1px solid black;
  text-align:center;
  padding-top:10px;
}

#loading_progress {
  width:0%;
  background-color:lightblue;
  position:absolute;
  height:30px;
  top:0px;
  left:0px;
}
body {
color:white;
background-color:black;
background-image:url(http://pupics.com/wp-content/uploads/2013/07/black-background-wallpaper-100.jpg);
/* http://fc08.deviantart.net/fs26/f/2008/041/5/a/Black_Background_3_by_sjunod.jpg */
}
</style>
<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"/>
<title>Platformer Example</title>
<p></p>
<center>
<div id='loading'>
	<div id='loading_container'>
		Loading...
		<div id='loading_progress'></div>
	</div>
</div>
</center>
<script src='./lib/quintus.js'></script>
<script src='./lib/quintus_sprites.js'></script>
<script src='./lib/quintus_scenes.js'></script>
<script src='./lib/quintus_input.js'></script>
<script src='./lib/quintus_anim.js'></script>
<script src='./lib/quintus_2d.js'></script>
<script src='./lib/quintus_touch.js'></script>
<script src='./lib/quintus_ui.js'></script>

<script>

function getSelectedText(text_array, id) {
	var buffer = '';
	for(var i=0; i< text_array.length; i++) buffer += (i == id ? '[ ' + text_array[i] + ' ]' : text_array[i]) + (i == text_array.length-1 ? '' : '\n');
	return buffer;
}


window.addEventListener("load",function() {
	var Q = window.Q = Quintus()
		.include("Sprites, Scenes, Input, 2D, Anim, Touch, UI")
		.setup( { width: 640, height: 480 });

	Q.SPRITE_PLAYER = 256;
	Q.SPRITE_PLAYER_SHOT = 512;
	Q.SPRITE_ENEMY_SHOT = 1024;

	Q.input.joypadControls();
	Q.input.keyboardControls();
	Q.input.touchControls({ controls:  [ [],[],[],[],['fire', 'action' ]] });

	// Déplacement simple pour le joueurs
	Q.component("simpleRPGControls", {
		defaults: {
			speed: 100
		},

		added: function() {
			var p = this.entity.p;
			Q._defaults(p,this.defaults);
			this.entity.on("step",this,"step");
			p.direction ='right';
		},

		step: function(dt) {
			var p = this.entity.p;
			if(Q.inputs['left']) {
				p.vx = -p.speed;
				p.direction = 'left';
			} else if(Q.inputs['right']) {
				p.direction = 'right';
				p.vx = p.speed;
			} else {
				p.vx = 0;
			}

			if(Q.inputs['up']) {
				p.vy = -p.speed;
				p.direction = 'up';
			} else if(Q.inputs['down']) {
				p.direction = 'down';
				p.vy = p.speed;
			} else {
				p.vy = 0;
			}
		}
	});

	// Les ennemis rebomdissent sur tous les bords
	Q.component('aiBounce2', {
		added: function() {
			this.entity.on("bump.right",this,"goLeft");
			this.entity.on("bump.top",this,"goDown");
			this.entity.on("bump.bottom",this,"goUp");
			this.entity.on("bump.left",this,"goRight");
		},
		goDown: 	function(col) { this.entity.p.vy = col.impact; },
		goUp: 		function(col) { this.entity.p.vy = -col.impact; },
		goLeft: 	function(col) { this.entity.p.vx = -col.impact; },
		goRight: 	function(col) { this.entity.p.vx = col.impact; }
	});

	// ## Player Sprite
	Q.Sprite.extend("Player",{
		init: function(p) {
			this.last_action = 0;
			this._super(p, {
				gravity:0,
				sprite: "hero",
				sheet: "hero"
			});
			this.add('2d, animation, simpleRPGControls');
			this.on("hit",function(collision) {
				// Si le héros rencontre un personnage non joueur ou un ennemi il choisit une action
				if(collision.obj.isA("NPC") || collision.obj.isA("Ennemy")) {
					if (Date.now() > this.last_action + 500) {
						var action_list = [];
						this.play('stand');
						if (collision.obj.p.discussion.length) action_list.push('Parler');
						if (collision.obj.isA("Ennemy")) action_list.push('Attaquer');
						action_list.push('Quitter');
						Q.stage(0).pause();
						Q.stageScene("actionList", 1, {
							x: Math.max(collision.obj.p.x, this.p.x) + this.p.w,
							y: Math.max(collision.obj.p.y, this.p.y),
							actions: action_list,
							discussion: collision.obj.p.discussion
						});
					}
				// Si le héros rencontre un objet il le prends
				} else if(collision.obj.isA("Loot")) {
					Q.stage(0).insert(
						new Q.LootText({
							x:collision.obj.p.x,
							y: collision.obj.p.y,
							label: '+' + collision.obj.p.val + ' '+	collision.obj.p.obj
						})
					);
					collision.obj.destroy();
				// Si le héros rencontre un téléporteur il se téléporte là bas
				} else if(collision.obj.isA("Teleporter")) {
					Q.stageScene(collision.obj.p.scene);
				}
			});
		},
		step: function(dt) {
			if (this.p.vx < 0) this.play('walk_left');
			else if (this.p.vx > 0) this.play('walk_right');
			else if (this.p.vy > 0) this.play('walk_down');
			else if (this.p.vy < 0) this.play('walk_up');
			else this.play('stand');
		}
	});


	// Un personnage non joueur
	Q.Sprite.extend("NPC",{
		init: function(p) {
			this._super(p, {
				gravity:0,
				asset: "npc1.png",
				text: "Replace this",
				discussion: []
			});
		}
	});

	// Un ennemy
	Q.Sprite.extend("Ennemy",{
		init: function(p) {
			this.last_shot = 0;
			this._super(p, {
				gravity:0,
				vx: 100,
				discussion: []
			});
			this.add('2d, aiBounce2');
		},
		isNear: function(x,y,distance) {
			return (Math.abs(x - this.p.x) <= distance && Math.abs(y - this.p.y) <= distance);
		}
	});

	// Un truc à ramasser
	Q.Sprite.extend("Loot",{
		init: function(p) {
			this._super(p, {
				gravity:0,
				asset: "gold.png",
				obj: 'gold',
				val: 20
			});
		}
	});

	Q.UI.Text.extend("LootText", {
		init: function(p) {
			this._super(p, {
				color: "yellow",
				size: 12,
				align: 'left'
			});
			var _this = this;
			setTimeout(function() { _this.destroy(); }, 1750);
		},
		step: function(dt) {
			this.p.y -= 20*dt;
		}
	});

	// Liste des actions
	Q.scene('actionList',function(stage) {
		var title = stage.options.title;
		var container = stage.insert(new Q.UI.Container({
			x: -100,
			y: -100,
			fill: "rgba(255,255,255,0.9)",
			border: 1
		}));
		var current_selected_text_id = 0;
		var text_zone = container.insert(
			new Q.UI.Text({
				x:20,
				y: 0,
				label: getSelectedText(stage.options.actions, 0),
				color: "black",
				size: 12,
				align: 'center'
			})
		);
		container.fit(10, 16);
		container.p.x = stage.options.x+container.p.cx;
		container.p.y = stage.options.y;
		setTimeout(function() {
			Q.input.on('down',stage,function(e) {
				current_selected_text_id = (current_selected_text_id == stage.options.actions.length -1 ? 0 : current_selected_text_id + 1);
				text_zone.p.label = getSelectedText(stage.options.actions, current_selected_text_id);
			});
			Q.input.on('up',stage,function(e) {
				current_selected_text_id = (current_selected_text_id == 0 ? stage.options.actions.length - 1 : current_selected_text_id - 1);
				text_zone.p.label = getSelectedText(stage.options.actions, current_selected_text_id);
			});
			Q.input.on('fire',stage,function(e) {
				if (stage.options.actions[current_selected_text_id] == 'Parler') {
					Q.stageScene("speakWith", 1, { discussion: stage.options.discussion} );
				} else if (stage.options.actions[current_selected_text_id] == 'Quitter') {
					Q.stage(0).unpause();
					// Pour éviter qu'on refasse un truc juste après avoir parlé
					Q("Player", 0).first().last_action = Date.now();
					Q.clearStage(1);
				}
			});
		}, 250);
	});


	// Systeme de discussion
	Q.scene('speakWith',function(stage) {
		var container = stage.insert(new Q.UI.Container({
			x: Q.width/2,
			y: 60,
			fill: "rgba(255,255,255,0.9)", // "rgba(0,0,0,0.8)"
				border: 1
		}));
		var img_npc = container.insert(
			new Q.Face({ sprite: stage.options.discussion[0].face, sheet: stage.options.discussion[0].face, x: 0, y: 0 })
		);

		var text = container.insert(
			new Q.UI.Text({
				x:0,
				y: 0,
				label: 	'' + stage.options.discussion[0].text,
				color: "black", // "white",
				size: 12,
				align: 'left'
			})
		);

		Q.input.on('fire',stage,function(e) {
			stage.options.discussion.shift();
			if (stage.options.discussion.length > 0) {
				Q.stageScene("speakWith", 1,
					{ text: stage.options.text, discussion: stage.options.discussion}
				);
			} else {
				Q.stage(0).unpause();
				// Pour éviter qu'on refasse un truc juste après avoir parlé
				Q("Player", 0).first().last_action = Date.now();
				Q.clearStage(1);
			}
		});

		container.fit(12, 60);
		text.p.x += 32;
		img_npc.p.x = 0 - container.p.cx + 36;
		img_npc.play('talk');

		setTimeout(function() {
			var container2 = stage.insert(new Q.UI.Container({
				x: Q.width/2,
				y: Q.height-30,
				fill: "rgba(255,255,255,0.9)",
				border: 1
			}));
			var text = container2.insert(
				new Q.UI.Text({
					x:0,
					y: 0,
					label: 	'Appuie sur espace pour continuer...',
					color: "black",
					size: 12,
					align: 'left'
				})
			);
			container2.fit(10, 10);
		}, 5000);
	});

	// Les tetes qui bougent
	Q.Sprite.extend("Face", {
		init: function(p) {
			this._super(p, { sprite: "none", sheet: "none"});
			this.add("animation");
		}
	});

	// Teleporter
	Q.Sprite.extend("Teleporter", {
		init: function(p) {
			this._super(p, {scene: 'none'});
		}
	});
	<?php require('./intro.js'); ?>
	<?php require('./levels.js'); ?>

	// Chargement initial
	Q.load("<?php require('assets.txt'); ?>", function() {

		Q.sheet("hero","hero.png",{tilew: 27, tileh: 31,  sx: 0, sy: 0});
		Q.animations('hero', {
			walk_down: { frames: [0,1,0,2], rate: 1/4},
			walk_up: { frames: [3,5,4,5], rate: 1/4},
			walk_left: { frames: [6,7,6,8], rate: 1/4},
			walk_right: { frames: [9,10,9,11], rate: 1/4},
			stand: { frames: [0], rate: 1/4},
		});

		Q.sheet("npc_face","npc_face.png",{tilew: 64, tileh: 64,  sx: 0, sy: 0});
		Q.animations('npc_face', {
			talk: { frames: [0,1,0,2,3,2,1,0,1], rate: 1/3}
		});

		Q.sheet("npc_face2","npc_face2.png",{tilew: 64, tileh: 64,  sx: 0, sy: 0});
		Q.animations('npc_face2', {
			talk: { frames: [0,1], rate: 1/3}
		});

		Q.sheet("player_face","player_face.png",{tilew: 64, tileh: 64,  sx: 0, sy: 0});
		Q.animations('player_face', {
			talk: { frames: [0,1], rate: 1/3}
		});

		Q.sheet("tiles","tiles.png", { tilew: 32, tileh: 32 });

		Q.stageScene("BTitle",0);
		Q.stageScene("Title",1);

	}, {
		progressCallback: function(loaded,total) {
			var element = document.getElementById("loading_progress");
			element.style.width = Math.floor(loaded/total*100) + "%";
		}
	});
});




</script>
<style>
  body { padding:0px; margin:0px; }
</style>
</head>
<body>
</body>
</html>
